package com.lemon.smartsafety.ui.activity.safe.data;

import android.app.PendingIntent;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.AnimationDrawable;
import android.nfc.NfcAdapter;
import android.nfc.Tag;
import android.nfc.tech.IsoDep;
import android.nfc.tech.MifareClassic;
import android.nfc.tech.MifareUltralight;
import android.nfc.tech.Ndef;
import android.nfc.tech.NdefFormatable;
import android.nfc.tech.NfcA;
import android.nfc.tech.NfcB;
import android.nfc.tech.NfcF;
import android.nfc.tech.NfcV;
import android.support.design.widget.AppBarLayout;
import android.support.v7.widget.Toolbar;
import android.util.Log;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.lemon.smartsafety.R;
import com.lemon.smartsafety.app.AppService;
import com.lemon.smartsafety.entity.safe.company.BindNfcEvent;
import com.lemon.smartsafety.tag.BaseTAG;
import com.lemon.smartsafetynew.ui.activity.base.NewBaseActivity;
import com.lemon.smartsafety.utils.common.StringUtils;

import butterknife.Bind;

public class BuildingCheckItemBindNfcActivity extends NewBaseActivity {


    @Bind(R.id.main_title)
    TextView mainTitle;
    @Bind(R.id.toolbar)
    Toolbar toolbar;
    @Bind(R.id.app_bar_layout)
    AppBarLayout appBarLayout;
    @Bind(R.id.img_nfc)
    ImageView imgNfc;


    private NfcAdapter mNfcAdapter = null;

    private PendingIntent pendingIntent;
    private IntentFilter[] mFilters;
    private String readResult = "";
    private boolean isFirst = true;

    private String[][] mTechLists;

    private int mNFC = 0;

    String strTag="";



    @Override
    protected void getBundleArgs() {
        if (getIntent().getExtras().containsKey(BaseTAG.COMMON_BASE_TAG)) {
            strTag = getIntent().getExtras().getString(BaseTAG.COMMON_BASE_TAG);
        }
    }

    @Override
    protected int getContentViewId() {
        return R.layout.activity_building_check_item_bind_nfc;
    }

    @Override
    protected void initTitleView() {
        setBarTitle("NFC");
    }

    @Override
    protected void initView() {
        mNfcAdapter = NfcAdapter.getDefaultAdapter(this);
        if (!checkNFCEnable()) {
            return;
        }
        //将被调用的Intent，用于重复被Intent触发后将要执行的跳转
        pendingIntent = PendingIntent.getActivity(this, 0, new Intent(this,
                getClass()).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), 0);
        //设定要过滤的标签动作，这里只接收ACTION_NDEF_DISCOVERED类型
        //IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_TECH_DISCOVERED);
        IntentFilter ndef = new IntentFilter(NfcAdapter.ACTION_NDEF_DISCOVERED);
        ndef.addCategory("*/*");
        mFilters = new IntentFilter[]{ndef};// 过滤器


        mTechLists = new String[][]{new String[]{NfcA.class.getName()}, new String[]{NfcB.class.getName()}, new String[]{NfcF.class.getName()}
                , new String[]{NfcV.class.getName()}, new String[]{MifareClassic.class.getName()}, new String[]{IsoDep.class.getName()}, new String[]{Ndef.class.getName()}
                , new String[]{MifareUltralight.class.getName()}, new String[]{NdefFormatable.class.getName()}};

        if (isFirst) {
            if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(getIntent()
                    .getAction())) {
                if (readTag(getIntent())) {
                    Log.e("readResult:", readResult);
                    try {
                        AppService.getBus().post(new BindNfcEvent(readResult,strTag));
                        mActivity.finish();
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                } else {
                    mHUDUtil.showErrorTip("NFC读取失败");
                }
            }
            isFirst = false;
        }

        imgNfc.setBackgroundResource(R.drawable.nfc_turn);
        AnimationDrawable _animaition = (AnimationDrawable)imgNfc.getBackground();
        _animaition.setOneShot(false);
        _animaition.start();//启动
    }

    @Override
    protected void initHttp() {

    }

    @Override
    protected void initList() {

    }

    @Override
    protected void loadList() {

    }

    @Override
    protected void refreshView() {

    }

    @Override
    protected void callFinish() {
        mActivity.finish();
    }


    /**
     * 读取NFC标签数据的操作
     *
     * @param intent
     * @return
     */
    private boolean readTag(Intent intent) {
        String intentActionStr = intent.getAction();
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intentActionStr)// NDEF类型

                || NfcAdapter.ACTION_TECH_DISCOVERED.equals(intentActionStr)// 其他类型

                || NfcAdapter.ACTION_TAG_DISCOVERED.equals(intentActionStr)) {// 未知类型
//            byte[] bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            //Android NFC API 10 以后对Tag 对象加入方法getID来获取id,所以还可以
            // 在intent中通过附加信息读取Tag标签对象，即获取扫描到的标签
            // 然后通过Tag对象读取id
            Tag tag = intent.getParcelableExtra(NfcAdapter.EXTRA_TAG);
            byte[] bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);//这是一个hex的字节数组
            if (bytesId == null || bytesId.length == 0) {
                bytesId = intent.getByteArrayExtra(NfcAdapter.EXTRA_ID);
            }
            try {
                if (bytesId != null) {
                    readResult = StringUtils.getHexString(bytesId);
                    Log.e("bytesId:", readResult);

                    String str = new String(bytesId);
                    Log.e("strbytesId:", readResult);
                    return true;
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
            //0412B50AB82A80 == 1
            //0416B50AB82A80 == 2
            return true;
        }

        return false;
    }

    private boolean checkNFCEnable() {
        if (mNfcAdapter == null) {
            Toast.makeText(mActivity, "设备没有NFC功能", Toast.LENGTH_SHORT).show();
            finish();
            return false;
        }
        if (mNfcAdapter != null && !mNfcAdapter.isEnabled()) {
            Toast.makeText(mActivity, "请开启设备NFC功能", Toast.LENGTH_SHORT).show();
            finish();
            return false;
        }
        return true;

    }


    /*
     * 有必要要了解onNewIntent回调函数的调用时机,请自行上网查询
     *  (non-Javadoc)
     * @see android.app.Activity#onNewIntent(android.content.Intent)
     */
    @Override
    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        if (NfcAdapter.ACTION_NDEF_DISCOVERED.equals(intent.getAction()) ||
                NfcAdapter.ACTION_TECH_DISCOVERED.equals(intent.getAction())) {
            if (readTag(intent)) {
                Log.e("readResult:", readResult);
                try {
                    AppService.getBus().post(new BindNfcEvent(readResult,strTag));
                    mActivity.finish();
                } catch (Exception e) {
                    e.printStackTrace();
                }

            } else {
                mHUDUtil.showErrorTip("NFC读取失败");
            }
        }

    }

    @Override
    protected void onResume() {
        super.onResume();
        // 前台分发系统,这里的作用在于第二次检测NFC标签时该应用有最高的捕获优先权.
        //打开前台发布系统，主线程里调用并且Activity在前台
        mNfcAdapter.enableForegroundDispatch(mActivity, pendingIntent, mFilters,
                mTechLists);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mNfcAdapter.disableForegroundDispatch(mActivity);//关闭前台发布系统
    }


}
